<template lang="pug">
  .CompleteFundWagesModal
    Modal(
      v-model="isShowCompleteFundWagesModal"
      :title="CompleteFundWagesModalTitle"
      class-name="vertical-center-modal"
      width="480"
    )
      .clearfix
        Form.ivu-row.has-rules-item2(ref="formData" :model="formData" :rules="rules" :label-width="130")
          FormItem.form-item.ivu-col(v-for="(item, index) of formItem" :label="item.label" :key="index" :class="item.style" :prop="item.prop" v-show="item.isShow")
            template(v-if="item.type === 'input'")
              Input(v-model="formData[item.model]" :placeholder="item.placeholder" clearable)
            template(v-if="item.type === 'select'")
              Select(v-model="formData[item.model]" :placeholder="item.placeholder" clearable)
                Option(v-for="(c_item, c_index) of arrListDown[item.options]" :key="c_index" :value="c_item.value") {{c_item.text}}
            template(v-if="item.type === 'textarea'")
              Input(v-model="formData[item.model]" :placeholder="item.placeholder" type="textarea" :rows="3")
            template(v-if="item.type === 'datePicker'")
              DatePicker.w-100(v-model="formData[item.model]" :placeholder="item.placeholder" type="date")
            template(v-if="item.type === 'inputnumber'")
              Input(v-model="formData[item.model]" type="number" :placeholder="actionType === 'view' ? '未填写' : item.placeholder" clearable)
            template(v-if="item.type === 'upload'")
              Row
                Col(span="24")
                  Upload(
                    ref="upload"
                    :max-size="10 * 1024"
                    :on-exceeded-size="handleMaxSizeTen"
                    :before-upload="handleBeforeUpload"
                    :on-success="uploadSuccess"
                    :action="'/api/TreatmentBasicsType/TreatmentAnnexUpload?categoryName='+formData.categoryName"
                    :show-upload-list="false"
                    :data="formData"
                    :headers="headers"
                  )
                    Input(v-model="formData[item.model].name" v-show="false")
                    Button.mr-20(type="info") 附件上传
                    Tag.mr-10(v-if="files.length > 0" v-for="(file,idx) of files" style='max-width:222px;white-space: pre-wrap;height:auto;')
                      span.pr-5 {{file.name}}
                      a(@click="handleDelFile(idx)")
                        Icon.btn-r-close(type="md-close")
                Col(span="24")
                  .text-gray-9 仅支持上传10M以内的文件
        
      .clearfix(slot="footer")
        Button(type="text" @click="cancel") 取消
        Button(type="primary" @click="handleSave" :loading="!isCanSubmit") 确定
</template>

<script>
import { Common } from '@/utils/common.js'
import dataApi from '@/api/data.js'
import { TreatmentApi } from '@/api/Treatment.api.js'
import { TreatmentEnjoyAuditApi } from '@/api/TreatmentEnjoyAudit.api.js'
import { TreatmentBasicsTypeApi } from '@/api/TreatmentBasicsType.api.js'
import { createNodeThead, editNodeThead } from '../tableHead'
import _cloneDeep from 'clone-deep'
import Cookies from 'js-cookie'

export default {
  name: 'CompleteFundWagesModal',

  watch: {
  },

  computed: {
  },

  data () {
    return {
      headers: {
        'Authorization': 'Bearer ' + Cookies.get('clientToken')
      },
      id: '',
      rowVersion: '',
      securityTypeCode: null,
      isShowCompleteFundWagesModal: false,
      CompleteFundWagesModalTitle: '公积金待遇办理完成',
      actionType: 'view',
      wagesId: '',
      monthOptions: {
        disabledDate (date) {
          return date && date.valueOf() < Date.now() - 86400000;
        }
      },
      formData: {
        completeTime: '',
        remarks: '',
        appraisalGrade: '',
        treatmentAmount: '',
        annexId: [],
        categoryName:'公积金待遇审核'
      },
      formItem: [
        { type: 'datePicker', label: '完成时间：', placeholder: '请选择完成时间', prop: 'completeTime', model: 'completeTime', style: 'ivu-col-span-24', isShow: true },
        { type: 'input', label: '备注：', placeholder: '请输入备注', prop: 'remarks', model: 'remarks', style: 'ivu-col-span-24', isShow: true },
        { type: 'input', label: '鉴定等级：', placeholder: '请输入鉴定等级', prop: 'appraisalGrade', model: 'appraisalGrade', style: 'ivu-col-span-24', isShow: true },
        { type: 'inputnumber', label: '待遇金额：', placeholder: '请输入待遇金额', prop: 'treatmentAmount', model: 'treatmentAmount', style: 'ivu-col-span-24', isShow: true },
        { type: 'upload', label: '附件：', placeholder: '请上传附件', prop: 'annexId', model: 'annexId', style: 'ivu-col-span-24', isShow: true },
      ],
      rules: {
        completeTime: [
          { required: true, message: '请选择完成时间', type: 'date', trigger: 'change' }
        ],
      },
      arrListDown: {
        tempOps: []
      },
      areaTree: [], // 中国所有城市树
      createNodeThead: _cloneDeep(createNodeThead),
      editNodeThead: _cloneDeep(editNodeThead),
      nodeTable: [],
      errorData: {
        errorId: '',
        isError: false,
        downLoadUrl: null
      },
      files: [],
      fileAnnexArr: [],
      isCanSubmit: true,
      
    }
  },

  mounted () {
  },

  methods: {
    // 监听所有调用的方法
    listenCall (methodsWords, param) {
      this[methodsWords](param)
    },

    cancel () {
      this.isShowCompleteFundWagesModal = false
    },

    async getModel (id) {
      let res = await TreatmentEnjoyAuditApi.model({id:id})
      console.log('model获取详情: ', res)
      if (res.status === 200 && res.data.success) {
        let annexId = []
        let attachmentList = res.data.data.attachmentList
        for (var i in attachmentList) {
          annexId[i]= attachmentList[i].id
          console.log(attachmentList[i])
          this.files.push(attachmentList[i])
          this.fileAnnexArr.push({
            Annex:attachmentList[i].id,
            Name:attachmentList[i].name
          })
        }
        console.log(this.files)
        this.formData={
          completeTime: res.data.data.completeTime,
          remarks: res.data.data.remarks,
          appraisalGrade: res.data.data.appraisalGrade,
          treatmentAmount: res.data.data.treatmentAmount,
          annexId: annexId,
          categoryName:'公积金待遇审核'
        }
      }
    },

    show (id) {
      console.log(id,'show')
      this.id = id
      this.isCanSubmit = true
      this.isShowCompleteFundWagesModal = true
      this.$refs.formData.resetFields()
      this.nodeTable = []
      this.files = []
      this.fileAnnexArr = []
    },

    // 日期选择
    handleChangeDatePicker (model, val) {
      console.log('model: ', model)
      console.log('val: ', val)
      this.formData[model] = val
    },

    handleMaxSizeTen () {
      this.$Message.error({
        content: '您上传的文件太大，上传文件大小不能超过10M',
        duration: 50,
        closable: true
      })
      this.files = []
      this.formData.annexId = []
      this.fileAnnexArr = []
    },

    // 批量导入-上传前文件
    handleBeforeUpload (file) {
      var str = file.name.substring(file.name.lastIndexOf('.'), file.name.length)
      if (['.exe'].indexOf(str) !== -1) {
        this.$Message.warning('文件格式不对')
        this.files = []
        this.formData.annexId = []
        this.fileAnnexArr = []
        console.log('this.files: ', this.files)
        console.log('this.formData.annexId: ', this.formData.annexId)
        console.log('this.fileAnnexArr: ', this.fileAnnexArr)
      } else {
        this.errorData.isError = false
        this.files.push(file)
      }
      // return false
    },

    // 上传成功
    uploadSuccess (res, row) {
      console.log('res: ', res)
      var fileName = res.Data.Name
      var str = fileName.substring(fileName.lastIndexOf('.'), fileName.length)
      if (res.Success) {
        if (['.xls', '.xlsx'].indexOf(str) !== -1) {
          var idArr = []
          this.fileAnnexArr.push({...res.Data, ...{TreatmentEnjoyLinkID: this.id, Annex: res.Data.Id}})
          this.fileAnnexArr.map(item => {
            delete item.Id
            idArr.push(item.Annex)
          })
          // this.formData.annexId = idArr.join(',')
          this.formData.annexId = idArr
        }
      } else {
        this.$Message.success(res.Message)
      }
    },

    // 普通附件下载
    accessoryDownload (url) {
      console.log('下载url: ', url)
      window.open(url, '_blank')
    },

    // 附件删除
    handleDelFile (idx) {
      let id = this.formData.annexId[idx]
      this.$Modal.confirm({
        title: '是否确认删除附件',
        onOk: () => {
          TreatmentBasicsTypeApi.treatmentDeleteAnnex({id:id}).then(res => {
            console.log('保存: ', res)
            if (res.data.success) {
              this.$Message.success(res.data.message)
              this.files.splice(idx, 1)
              this.fileAnnexArr.splice(idx, 1)
              this.formData.annexId.splice(idx, 1)
            } else {
              this.$Message.error({
                content: res.data.message,
                duration: 10,
                closable: true
              })
            }
          })
        }
      })
    },

    // 保存
    handleSave () {
      console.log(this.id)
      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.isCanSubmit = false
          var params = {
            Id: this.id,
            RowVersion: this.rowVersion,
            ...this.formData
          }
          params.annexId = params.annexId.join(',')
          TreatmentEnjoyAuditApi.save({...params}).then(res => {
            console.log('保存: ', res)
            if (res.data.success) {
              this.$Message.success(res.data.message)
              this.$emit('query')
              this.isShowCompleteFundWagesModal = false
            } else {
              this.isCanSubmit = true
              this.$Message.error({
                content: res.data.message,
                duration: 10,
                closable: true
              })
            }
          })
        } else {
          this.isCanSubmit = true
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>

</style>
